// components/ProtectedRoute.js
import React, { useEffect, useState } from 'react';
import { Navigate } from 'react-router-dom';
import axios from 'axios';

const ProtectedRoute = ({ component: Component, requiredPermission, location }) => {
    const [isAuthenticated, setIsAuthenticated] = useState(false);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const checkAuth = async () => {
            const currentUser = JSON.parse(localStorage.getItem('currentUser'));
            const token = currentUser?.token;

            if (token) {
                axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

                try {
                    const response = await axios.get(`http://localhost:8080/api/another/route-check-permission?permission=${requiredPermission}`);
                    if (response.status === 200) {
                        setIsAuthenticated(true);
                    } else {
                        setIsAuthenticated(false);
                    }
                } catch (error) {
                    setIsAuthenticated(false);
                }
            } else {
                setIsAuthenticated(false);
            }

            setIsLoading(false);
        };

        checkAuth();
    }, [requiredPermission]);

    if (isLoading) {
        return <div>Loading...</div>;
    }

    if (!isAuthenticated) {
        return <Navigate to={{ pathname: '/404', state: { from: location } }} replace />;
    }

    return <Component />;
};

export default ProtectedRoute;